/**
 * ThreadPool.java
 * com.tempus.ubp.dps.newsearch.thread
 *
 * Function： TODO 
 *
 *   ver     date      		author
 * ──────────────────────────────────
 *   		 2016年12月1日 		chenyingchun
 *
 * Copyright (c) 2016, TNT All Rights Reserved.
*/

package com.uoko.common.thread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * <p>
 * 为了方便基础级的使用,就用了工具类的方式处理。配合lamda表达式,可以一行代码完成同步执行转异步执行！。
 * </p>
 *
 * @author chenyingchun
 * Email qiaohai@uoko.com
 * created by 2018/6/6 0006
 */
public class ThreadPools {

	/**
	 * 查询相关的线程池,Fixed的是固定线程池,适合做持续不断来的任务和外部接口平峰。如果根据自己业务需要可以灵活选择其他的。
	 */
	private static ExecutorService threadPool = Executors.newCachedThreadPool();

	/**
	 * @return
	 */
	public static ExecutorService getThreadPool() {

		return threadPool;
	}

	/**
	 * @param task
	 * @return
	 */
	public static <T> Future<T> submitTask(Callable<T> task) {

		return threadPool.submit(task);
	}

	/**
	 * 不返回结果的任务
	 * 
	 * @param command
	 */
	public static void executeTask(Runnable command) {

		threadPool.execute(command);
	}

	/**
	 * 获取submitTask执行的执行结果。
	 * 
	 * @param future
	 * @return
	 * @throws InterruptedException
	 * @throws ExecutionException
	 */
	public static <k> k getFutureResultObject(Future<k> future) throws Exception {

		try {
			return future.get();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw e;
		} catch (ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw e;
		}

	}

	/**
	 * 获取由submitTask执行的结果,再设定的超时时间内返回最后结果，超时时间单位为毫秒
	 * 
	 * @param future
	 * @param timeout
	 * @return
	 * @throws InterruptedException
	 * @throws ExecutionException
	 * @throws TimeoutException
	 */
	public static <k> k getFutureResultObject(Future<k> future, long timeout) throws Exception {

		try {
			// return getFutureResultObject(future);
			return future.get(timeout, TimeUnit.MILLISECONDS);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw e;
		} catch (ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw e;
		} catch (TimeoutException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw e;
		}

	}
}
